<template>
  <div>
    <div class="head">
      <el-row>
        <el-col :span="6">
          <el-input placeholder="请输入内容" v-model="getDataPar.keyword" class="input-with-select">
            <el-button slot="append" @click="conditionSearch" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="5" :offset="1">
          <span>性别：</span>
          <el-select v-model="getDataPar.gender" placeholder="请选择" @change="conditionSearch">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"> </el-option>
          </el-select>
        </el-col>
        <!-- <el-col :span="5">
          <span>时间：</span>
          <el-select v-model="timeSelectVal" placeholder="请选择">
            <el-option v-for="item in timeOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"> </el-option>
          </el-select>
        </el-col> -->
        <el-col :span="1">
          <el-button type="warning" icon="el-icon-refresh" @click="handleRef">重置</el-button>
        </el-col>
      </el-row>
      <div style="margin-bottom: 10px">
        <el-button icon="el-icon-plus" @click="handleAdd" type="primary">添加</el-button>
        <!-- <el-button icon="iconfont icon-daoru" type="success">导入</el-button>
        <el-button icon="iconfont icon-daochu" @click="handleExport" type="success">导出</el-button> -->
        <el-button icon="el-icon-delete" @click="handleBatchDel" type="danger">批量删除</el-button>
      </div>
    </div>
    <div class="table">
      <el-table height="400px" v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" :data="tableData" :border="true" stripe style="width: 100%" tooltip-effect="dark" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="create_time" label="创建日期" min-width="140"> </el-table-column>
        <el-table-column prop="name" label="用户名" min-width="120">
          <template slot-scope="scoped">
            <el-tag>
              {{ scoped.row.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" min-width="120"> </el-table-column>
        <el-table-column prop="uid" label="用户编号" min-width="120"> </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="150"> </el-table-column>
        <el-table-column prop="gender" label="性别" min-width="70"> </el-table-column>
        <el-table-column prop="avatar" label="头像" min-width="100">
          <template slot-scope="scoped">
            <el-avatar fit="cover" :size="58" :src="scoped.row.avatar"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="300">
          <template slot-scope="scoped">
            <el-button icon="el-icon-edit" @click="handleEdit(scoped.row)">编辑</el-button>
            <el-button icon="el-icon-delete" @click="handleDel(scoped.row)" type="danger">删除</el-button>
            <el-button icon="el-icon-refresh" @click="resetPassword(scoped.row)" type="warning">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="getDataPar.currentPage" :page-sizes="[15, 30, 50, 100]" :page-size="getDataPar.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </div>
    <!-- 添加或修改弹框 -->
    <el-dialog top="20px" :title="dialogTitle + '用户'" :visible.sync="dialogVisible" width="30%" @close="handleClose">
      <add-and-edit ref="bulletBox" @submit="submit" :ruleForm="editObj"></add-and-edit>
    </el-dialog>
  </div>
</template>

<script>
import { adminListPage, delAdmin, addOrEditAdmin, batchDelete, resetPassword, exportAdmin } from '@/api/adminApi.js'

import addAndEdit from './AddAndEdit.vue'
export default {
  data() {
    return {
      loading: true,
      timeSelectVal: '',
      dialogVisible: false, //添加和修改弹窗控制开关
      editObj: {}, //修改行对象信息
      dialogTitle: '添加',
      options: [
        {
          value: 0,
          label: '全部',
        },
        {
          value: 1,
          label: '女生',
        },
        {
          value: 2,
          label: '男生',
        },
      ],
      timeOptions: [
        {
          value: '1',
          label: '本周',
        },
        {
          value: '2',
          label: '本月',
        },
        {
          value: '3',
          label: '近半年',
        },
        {
          value: '4',
          label: '近一年',
        },
      ],
      tableData: [],
      selectTableRow: [],
      userInfo: {},
      getDataPar: {
        pageSize: 15,
        currentPage: 1,
        keyword: '',
        gender: 0,
      },
      total: 0,
    }
  },
  components: {
    addAndEdit,
  },
  created() {
    this.userInfo = this.userInfo = this.$sessionStorage('get', 'userInfo') ? this.$sessionStorage('get', 'userInfo') : {}
    this.getData()
  },
  methods: {
    getData() {
      this.loading = true
      adminListPage(this.getDataPar).then((res) => {
        if (res.data.code != 200) return this.$message.error('数据请求失败')
        this.loading = false
        this.tableData = res.data.data.records
        this.total = res.data.data.total
        this.tableData.forEach((item) => {
          item.create_time = this.$moment(item.create_time).format('YYYY-MM-DD HH:mm:ss')
        })
      })
    },
    handleSelectionChange(val) {
      this.selectTableRow = val
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.getDataPar.pageSize = val
      this.getDataPar.currentPage = 1
      this.getData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.getDataPar.currentPage = val
      this.getData()
    },
    //关键字、性别、时间筛选
    conditionSearch() {
      this.getData()
    },
    //重置条件筛选
    handleRef() {
      this.getDataPar = {
        pageSize: 15,
        currentPage: 1,
        keyword: '',
        gender: 0,
      }
      this.getData()
    },
    //添加
    handleAdd() {
      this.dialogTitle = '添加'
      this.dialogVisible = true
      this.editObj = {
        name: '',
        uid: '',
        phone: '',
        email: '',
        gender: '男',
        avatar: '',
        password: '',
      }
    },
    //修改
    handleEdit(val) {
      this.dialogTitle = '修改'
      this.dialogVisible = true
      this.editObj = JSON.parse(JSON.stringify(val))
    },
    //导出
    handleExport() {
      exportAdmin().then((res) => {})
    },
    //删除
    handleDel(row) {
      this.$confirm(`确定删除${row.name}用户吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          delAdmin({ id: row.id }).then((res) => {
            if (res.data.code != 200) return this.$message.error(`删除${row.name}失败！！！`)
            this.$message.success(`角色 ${row.name} 删除成功!`)
            this.getData()
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    //批量删除
    handleBatchDel() {
      this.$confirm(`确定此操作吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          let idList = []
          let tips = ''
          this.selectTableRow.forEach((item, i) => {
            idList.push(item.id)
            if (i == this.selectTableRow.length - 1) {
              tips += item.name
            } else {
              tips += item.name + ','
            }
          })
          batchDelete(idList).then((res) => {
            if (res.data.code != 200) return this.$message.error(`批量删除失败！！！`)
            this.$message.success(`${tips} 角色已被删除`)
            this.getData()
          })
        })
        .catch(() => {
          this.$message.info('已取消批量删除')
        })
    },
    //提交表单，添加或编辑
    submit(formData) {
      this.dialogVisible = false
      let _this = this
      addOrEditAdmin(formData).then((res) => {
        if (res.data.code != 200) return this.$message.error(`${this.dialogTitle}失败！！！`)
        this.$message.success(`${this.dialogTitle}成功`)
        _this.getData()
        //如果修改的是当前登录的管理员则更新存储信息
        if (formData.id && formData.id == this.userInfo.id) {
          this.$emit('upUserInfo', formData.id)
        }
      })
    },
    //重置密码
    resetPassword(row) {
      this.$confirm(`确定重置 “${row.name}” 用户密码吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          resetPassword(row.id).then((res) => {
            if (res.data.code != 200) return this.$message.error(`重置${row.name}用户密码失败！！！`)
            if (res.data.data == '1') {
              this.$message.warning(`当前用户密码已被修改，请重新登录`)
              sessionStorage.clear()
              this.$router.push('/login')
            } else {
              this.$message.success(`重置${row.name}用户密码成功`)
              this.getData()
            }
          })
        })
        .catch(() => {
          this.$message.info('已取消重置密码')
        })
    },
    //关闭弹框
    handleClose() {
      this.$refs.bulletBox.resetForm()
    },
  },
}
</script>

<style lang="less" scoped>
.block {
  margin-top: 15px;
}
</style>